define [
  'views/base/view'
  'text!templates/layout.html'
  'lib/dao_factory'
  'daos/utils_dao'
], () ->

  'use strict'

  # Imports
  # =============================================================
  View       = require 'views/base/view'
  template   = require 'text!templates/layout.html'
  DaoFactory = require 'lib/dao_factory'
  UtilsDao   = DaoFactory.getDAOByName 'utils_dao'

  MENU_PARENTS =
    adm:
      id    : 'menu-adm'
      label : 'Menu'

  MENU_ITENS = [
      label : 'Movimentos'
      roles : ['ROLE_ADMINISTRADOR']
      href  : '#movimento'
      parent: MENU_PARENTS.adm
    ,
      label : 'Usuário'
      roles : ['ROLE_ADMINISTRADOR']
      href  : '#usuario'
      parent: MENU_PARENTS.adm
    ,
      label : 'Sair'
      roles : ['ROLE_ADMINISTRADOR']
      href  : '#logout'
      parent: MENU_PARENTS.adm
  ]

  class LayoutView extends View

    # Override Attributtes
    # =============================================================

    template  : template
    container : '#app-container'

    # Override Methods
    # =============================================================

    initialize: ->
      super

    afterRender: ->
      super
      if window.userAuthorities
        @updateMenu window.userAuthorities
      @subscribeEvent 'layout:updateMenu', @updateMenu
      @subscribeEvent 'hide:menu', @hideMenu
      @subscribeEvent 'show:menu', @showMenu

    cacheDOMElements: ->
      _.extend super,
        $navbarContainer: $ '.navbar-collapse ul.navbar-nav'
        $navbar : $ '.navbar'

    # Additional Methods
    # =============================================================

    _appendMenuItem: (menu)->
      menuHTML = "<li><a href=\"#{menu.href}\">#{menu.label}</a></li>"

      if menu.parent and $("##{menu.parent.id}").length
        $("##{menu.parent.id}").append menuHTML
      else if menu.parent
        @DOMElements.$navbarContainer.append """
          <li class="dropdown">
            <a href="#" class="dropdown-toggle" data-toggle="dropdown">#{menu.parent.label} <span class="caret"></span></a>
            <ul class="dropdown-menu" id="#{menu.parent.id}"></ul>
          </li>
        """
        $("##{menu.parent.id}").append menuHTML
      else
        @DOMElements.$navbarContainer.append menuHTML

    updateMenu: (authorities) ->
      @DOMElements.$navbarContainer.empty()

      return unless authorities and _.isArray(authorities) and authorities.length

      for a in authorities
        authority = a.authority

        for menu in MENU_ITENS
          @_appendMenuItem menu if _.indexOf(menu.roles, a.authority) >= 0

    hideMenu: ->
      @DOMElements.$navbar.hide()

    showMenu: ->
      @DOMElements.$navbar.show()
